package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.sys.models.dto.SysUserRoleDTO;
import com.yt.sys.models.service.ISysUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.ISysUserService;
import com.yt.sys.models.bo.SysUserBO;
import com.yt.sys.models.dto.SysUserDTO;
import com.yt.sys.models.bo.SysUserSaveBO;
import com.yt.sys.models.bo.SysUserStatusUpdateRequest;
import com.yt.sys.models.bo.SysUserDeleteRequest;
import com.yt.sys.models.bo.SysUserUpdateRequest;
import com.yt.order.models.dto.WorkOrderInfoDTO;
import com.yt.order.models.service.IWorkOrderInfoService;
import org.springframework.beans.BeanUtils;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 用户信息控制器
 *
 * @author yzz
 * @Date 2025-09-03 14:08:47
 */

@RestController
@RequestMapping("/api/sysUser")
@Slf4j
@Api(value = "SysUserApiController",tags = "用户信息Api接口")
public class SysUserApiController {

    @DubboReference
    private ISysUserService sysUserService;
    
    @DubboReference
    private ISysUserRoleService sysUserRoleService;
    
    @DubboReference
    private IWorkOrderInfoService workOrderInfoService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<SysUserDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        SysUserDTO dto = sysUserService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "用户信息列表",notes = "用户信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<SysUserDTO>> queryPageList(SysUserBO bo){
        Wrapper<SysUserDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<SysUserDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = sysUserService.selectPage(page, wrapper);

        return new Result<>(page);
    }

    @ApiOperation(value = "用户信息列表",notes = "用户信息列表")
    @PostMapping("/listAll")
    public Result<List<SysUserDTO>> listAll(){
        List<SysUserDTO> list = sysUserService.selectList(null);
        return new Result<>(list);
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加用户信息", notes = "添加用户信息")
    public Result<Boolean> add(@RequestBody @Valid SysUserSaveBO saveBO) {
        boolean result = sysUserService.add(saveBO);
        return new Result<>(result);
    }

    @PostMapping("/update")
    @ApiOperation(value = "编辑用户信息", notes = "编辑用户信息")
    public Result<Boolean> update(@RequestBody @Valid SysUserUpdateRequest request) {
        if (request.getId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        SysUserDTO dto = sysUserService.selectById(request.getId());
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100003);
        }

        // 将请求参数复制到DTO对象中
        BeanUtils.copyProperties(request, dto);
        dto.setUpdateTime(new Date());
        
        boolean result = sysUserService.updateById(dto);
        return new Result<>(result);
    }
    
    @PostMapping("/updateStatus")
    @ApiOperation(value = "更新用户状态", notes = "更新用户状态")
    public Result<Boolean> updateStatus(@RequestBody @Valid SysUserStatusUpdateRequest request) {
        if (request.getId() == null || request.getStatus() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        SysUserDTO dto = sysUserService.selectById(request.getId());
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100003);
        }

        dto.setStatus(request.getStatus());
        dto.setUpdateTime(new Date());
        boolean result = sysUserService.updateById(dto);
        return new Result<>(result);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除用户", notes = "删除用户")
    public Result delete(@RequestBody @Valid SysUserDeleteRequest request) {
        if (request.getId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        SysUserDTO dto = sysUserService.selectById(request.getId());
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100003);
        }

        // 先删除用户角色关联记录
        try {
            EntityWrapper<SysUserRoleDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("user_id", request.getId());
            sysUserRoleService.delete(wrapper);
        } catch (Exception e) {
            log.error("删除用户角色关联记录失败", e);
            return new Result<>(CodeEnum.FAIL.getCode(), "删除用户关联数据失败");
        }

        // 删除与该用户相关的工单信息（dispatcher_id 或 employee_id 为该用户ID的记录）
        try {
            // 这里应该调用工单服务删除相关工单
            // 由于没有直接的dubbo引用，我们使用注解引入
            // 删除作为调度员的工单记录
            EntityWrapper<WorkOrderInfoDTO> workOrderWrapper1 = new EntityWrapper<WorkOrderInfoDTO>();
            workOrderWrapper1.eq("dispatcher_id", request.getId());
            workOrderInfoService.delete(workOrderWrapper1);
            
            // 删除作为员工的工单记录
            EntityWrapper<WorkOrderInfoDTO> workOrderWrapper2 = new EntityWrapper<WorkOrderInfoDTO>();
            workOrderWrapper2.eq("employee_id", request.getId());
            workOrderInfoService.delete(workOrderWrapper2);
        } catch (Exception e) {
            log.error("删除用户相关工单记录失败", e);
            return new Result<>(CodeEnum.FAIL.getCode(), "删除用户相关工单记录失败");
        }

        // 物理删除用户记录
        boolean flag = sysUserService.deleteById(request.getId());
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @PostMapping("/getByUserName")
    @ApiOperation(value = "根据用户姓名查找", notes = "根据用户姓名查找")
    @ApiImplicitParam(name = "userName", value = "用户姓名", required = true, paramType = "query", dataType = "String")
    public Result<List<SysUserDTO>> getByUserName(@RequestParam("userName") String userName) {
        if (userName == null || userName.trim().isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        Wrapper<SysUserDTO> wrapper = new EntityWrapper<>();
        wrapper.like("user_name", userName);
        List<SysUserDTO> users = sysUserService.selectList(wrapper);

        return new Result<>(users);
    }
}